package com.example.myapplication.flow

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.orhanobut.logger.Logger
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class Flowviewmodel0923 : ViewModel() {
    var count1 = 0
    var count2 = 0


    val state1 = MutableStateFlow("0")
    val state2 = MutableStateFlow("")


    fun senddata1() {
        count1++
        state1.value = "senddata1== $count1"
    }

    fun senddata2() {
        count2++
        state2.value = "senddata1== $count2"
    }

    fun flow1() {
        viewModelScope.launch {
            flow {
                emit("a")
                throw Exception("emit")
            }.transform {
//                throw Exception("transform")
                emit(it + "transform")
            }.catch {
                Logger.e("Flowviewmodel0923===flow1: " + it.message);
            }.collect {
                Logger.d("Flowviewmodel0923===flow1: $it");
            }
        }
    }

    fun flow2() {

    }

    fun countDownCoroutines(
        total: Int, scope: CoroutineScope, onTick: (Int) -> Unit,
        onStart: (() -> Unit)? = null,
        onFinish: (() -> Unit)? = null
    ): Job {
        return flow {
            for (i in total downTo 0) {
                emit(i)
                kotlinx.coroutines.delay(1000)
            }

        }.flowOn(Dispatchers.Main)
            .onStart {
                onStart?.invoke()
            }.onCompletion {
                onFinish?.invoke()
            }.onEach {
                onTick.invoke(it)
            }
            .launchIn(scope)

    }

}